from PyQt4.QtGui import QWidget, QFrame, QMainWindow, QVBoxLayout, QFont, QGridLayout, QLabel, QSizePolicy, QSpacerItem, QFormLayout
import S3DPath
from S3D import QtHelper
from S3D.Tools.Sound.EventSearcher.UI.ResultsWidget import Ui_ResultsWidget

#RESULT_ITEM_FONT = QFont("Comic Sans MS", 10)
RESULT_ITEM_FONT = QFont("Verdana", 10)
RESULT_ITEM_FONT.setBold(True)
ATTR_NAME_FONT   = QFont("Verdana", 7)
ATTR_NAME_FONT.setBold(True)
ATTR_VALUE_FONT  = QFont("Verdana", 7)

class ResultInfo:
    __slots__ = ("name", "info")

    def __init__(self, name, info):
        self.name = name
        self.info = info

class ResultItemWidget(QWidget):
    def __init__(self, info):
        super(ResultItemWidget, self).__init__()

        grid = QVBoxLayout(self)
        nameLabel = QLabel(info.name)
        nameLabel.setFont(RESULT_ITEM_FONT)
        grid.addWidget(nameLabel)

        form = QFormLayout()
        form.setContentsMargins(30, 0, 0, 5)
        for label, value in info.info:
            l = QLabel(label + ':');    l.setFont(ATTR_NAME_FONT)
            v = QLabel(value);          v.setFont(ATTR_VALUE_FONT)
            form.addRow(l, v)
        grid.addLayout(form)

        self.layout().setContentsMargins(0, 0, 0, 0)

class ResultsWidget(QWidget):
    def __init__(self, parent=None):
        super(ResultsWidget, self).__init__(parent)

        self.ui = Ui_ResultsWidget()
        self.ui.setupUi(self)

        self.resList = []

    def setResults(self, resList):
        self.resList = resList
        self.updateList()

    def updateList(self):
        self.hide()

        resultsLayout = self.ui.resultsLayout

        # clear all
        while True:
            item = resultsLayout.takeAt(0)
            if item is None: break

            widget = item.widget()
            if widget: widget.close()

        for index, info in enumerate(self.resList):
            if index >= 100:
                break

            item = ResultItemWidget(info)
            resultsLayout.addWidget(item)

        resultsLayout.addItem(QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Expanding))

        self.show()

if __name__ == '__main__':
    def makeRes(index):
        attrs = [("Name %d" % k, "attr_val_%d" % k) for k in range(5)]
        return ResultInfo("event_%d" % index, attrs)

    resList = [makeRes(k) for k in range(100)]

    wnd = QMainWindow()
    results = ResultsWidget(wnd)
    results.setResults(resList)

    wnd.setCentralWidget(results)
    wnd.show()
    
    QtHelper.qApp.exec_()